/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mantechhelpdesk.bean;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UICommand;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import mantechhelpdesk.dao.ArticlesDao;
import mantechhelpdesk.dao.DbConnection;
import mantechhelpdesk.entity.Articles;

/**
 *
 * @author DinhThang
 */
public class ArticlesBean {

    private Articles article = null;
    private List<Articles> articlesList;
    private ArticlesDao articlesDao;
    private Connection conn;
    // Paging
    private int totalRows;
    private int firstRow = 0;
    private int rowsPerPage;
    private int totalPages;
    private int pageRange;
    private Integer[] pages;
    private int currentPage;

    /**
     * Creates a new instance of ArticlesBean
     */
    public Articles getArticle() {
        return article;
    }

    public void setArticle(Articles article) {
        this.article = article;
    }

    public List<Articles> getArticlesList() {
        if (articlesList == null) {
            loadDataList(); // Preload page for the 1st view.
        }
        return articlesList;
    }

    public void setArticlesList(List<Articles> articlesList) {
        this.articlesList = articlesList;
    }

    public ArticlesBean() {
        try {
            // Set default values somehow (properties files?).
            rowsPerPage = 10; // Default rows per page (max amount of rows to be displayed at once).
            pageRange = 10; // Default page range (max amount of page links to be displayed at once).

            article = new Articles();
            articlesDao = new ArticlesDao();
            conn = DbConnection.getConnection();
            //articlesList = articlesDao.loadAll(conn);
            loadDataList();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String addNew() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpSession session = request.getSession(true);
            Object attribute = session.getAttribute("HelpDeskLogin");

            Calendar now = GregorianCalendar.getInstance();
            article.setCreateTime(now.getTime());
            article.setUserID(Integer.parseInt(attribute.toString()));
            articlesDao.create(conn, article);
            //articlesList = articlesDao.loadAll(conn);
            loadDataList();
            ct.addMessage("", new FacesMessage("Article addnew Success!"));
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot addnew Article!"));
        }
        return "articlesAddBack";
    }

    public String delete() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            articlesDao.delete(conn, article);
            ct.addMessage("", new FacesMessage("Article delete Success!"));
            //articlesList = articlesDao.loadAll(conn);            
            loadDataList();
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot delete Article!"));
        }
        return "articlesDelBack";
    }

    public String update() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            articlesDao.save(conn, article);
            articlesList = articlesDao.loadAll(conn);
            ct.addMessage("", new FacesMessage("Article update Success!"));
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot update Article!"));
        }
        return "articlesEditBack";
    }

    public String prepareData4Delete() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            article = articlesDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "articlesDel";
    }

    public String prepareData4Update() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            article = articlesDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "articlesEdit";
    }

    public String prepareData4View() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            article = articlesDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "articlesView";
    }

    private void loadDataList() {

        // Load list and totalCount.
        try {
            articlesList = articlesDao.loadAllByStartEnd(firstRow, firstRow + rowsPerPage, conn);
            totalRows = articlesDao.count(conn);
        } catch (Exception e) {
            throw new RuntimeException(e); // Handle it yourself.
        }

        // Set currentPage, totalPages and pages.
        currentPage = (totalRows / rowsPerPage) - ((totalRows - firstRow) / rowsPerPage) + 1;
        totalPages = (totalRows / rowsPerPage) + ((totalRows % rowsPerPage != 0) ? 1 : 0);
        int pagesLength = Math.min(pageRange, totalPages);
        pages = new Integer[pagesLength];

        // firstPage must be greater than 0 and lesser than totalPages-pageLength.
        int firstPage = Math.min(Math.max(0, currentPage - (pageRange / 2)), totalPages - pagesLength);

        // Create pages (page numbers for page links).
        for (int i = 0; i < pagesLength; i++) {
            pages[i] = ++firstPage;
        }
    }

    private void page(int firstRow) {
        this.firstRow = firstRow;
        loadDataList(); // Load requested page.
    }

    public int getTotalRows() {
        return totalRows;
    }

    public int getFirstRow() {
        return firstRow;
    }

    public int getRowsPerPage() {
        return rowsPerPage;
    }

    public Integer[] getPages() {
        return pages;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getTotalPages() {
        return totalPages;
    }

// Setters ————————————————————————————
    public void setRowsPerPage(int rowsPerPage) {
        this.rowsPerPage = rowsPerPage;
    }

    public void page(ActionEvent event) {
        page(((Integer) ((UICommand) event.getComponent()).getValue() - 1) * rowsPerPage);
    }
}